define(['app'], function(app) {
	'use strict';

	var controller = function controller($scope, Aftalkagain, $stateParams, GoPage, GoDialog, GoPicture) {
		
		$scope.id = $stateParams.id;
		$scope.type = $stateParams.type;
		$scope.input = new Object();
		$scope.input.uploads = new Array(); //存放图片id，要提交的
		$scope.input.uploads_show = new Array(); //存放图片url，显示用
		$scope.input.comments = new Array(); //评价内容数据
		
		//数据初始化
		$scope.init_data = function() {
			if($scope.type == 1) {//单个
				Aftalkagain.get_comment($scope.id, function(data) {
					$scope.order = data.result;
//					console.log(data)
				});
			} else {//多个
				Aftalkagain.get_order($scope.id, function(data) {
					$scope.orders = data;
					//console.log(data)
				});
			}
		}
		$scope.init_data(); //必须在定义之后

		//图片上传
		$scope.addStoreImg = function(index) {
			if(!($scope.input.uploads[index] instanceof Array)) { //让每个元素都为数组
				$scope.input.uploads[index] = new Array();
			}
			if(!($scope.input.uploads_show[index] instanceof Array)) { //让每个元素都为数组
				$scope.input.uploads_show[index] = new Array();
			}
			if($scope.input.uploads[index].length >= 4) {
				GoDialog.toast("最多只能晒图4张！");
				return;
			}
			GoPicture.upload(function(res) {
				if(!res.success) {
					GoDialog.alert("提示",res.msg);
					return;
				}
				$scope.input.uploads_show[index].push(res.result.image_src); //显示用
				$scope.input.uploads[index].push(res.result.image_id);
			});
		}

		//商品跳转
		$scope.onshow_detail = function(goods_id) {
			GoPage.go_states("productdetail", {
				"goods_id": goods_id,
				'type': "goods"
			});
		};

		///图片放大
		$scope.showmaximg = function(imgUrl) {
			GoDialog.showBigImg(imgUrl);
		}
		//图片删除
		$scope.delimg = function(parent_index, index) {
			$scope.input.uploads[parent_index].splice(index, 1);
			$scope.input.uploads_show[parent_index].splice(index, 1);
		}

		//保存
		$scope.save = function() {
			$scope.updateParams = new Array();
			if($scope.type == 1) {
				$scope.updateParams[0] = new Object();
				$scope.updateParams[0].comment_id = $scope.order.comment_id;
				$scope.updateParams[0].comment = $scope.input.comments[0];
				$scope.updateParams[0].image = $scope.input.uploads[0];
			} else {
				for(var i = 0; i < $scope.orders.goods.length; i++) {
					$scope.updateParams[i] = new Object;
					$scope.updateParams[i].comment_id = $scope.orders.goods[i].discuss_info[0].comment_id;
					$scope.updateParams[i].comment = $scope.input.comments[i];
					$scope.updateParams[i].image = $scope.input.uploads[i];
				}
			}
			Aftalkagain.send_comment($scope.updateParams, function(data) {
				if(data.success) {
					GoDialog.toast("发表成功！");
					$scope.input = new Object();//初始化，避免再次进来还是之前提交的数据
					GoPage.go_states("comment");
				} else {
					GoDialog.toast(data.msg);
				}
			});
		}
		

	}

	controller.$inject = ['$scope', 'Aftalkagain', '$stateParams', 'GoPage', 'GoDialog', 'GoPicture'];

	return app.registerController("aftalkagainctrl", controller);
});